/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.openmrs.module.basicmodule.DSS.Interpreter.Function;

import org.openmrs.module.basicmodule.DSS.Interpreter.InterpreterVisitor;
import org.openmrs.module.basicmodule.DSS.Interpreter.SymbolTable;
import org.openmrs.module.basicmodule.DSS.ast.IdTree;
import org.openmrs.module.basicmodule.DSS.ast.ListTree;
import org.openmrs.module.basicmodule.DSS.ast.LiteralTree;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Stephen
 */
public class LengthFunction extends Function {
    @Override
    public Object execute(ArrayList args) {
        try {
            if (args.get(0).getClass() == Class.forName("ast.IdTree")) {
                String varName = ((IdTree) args.get(0)).getSymbol().toString();
                String type = SymbolTable.Scope.getVarType(varName);
                if (type.equalsIgnoreCase("string")) {
                    String val = (String) SymbolTable.Scope.getVarValue(varName);
                    return Integer.toString(val.length());
                } else if (type.equalsIgnoreCase("list")) {
                    ArrayList val = (ArrayList) SymbolTable.Scope.getVarValue(varName);
                    return Integer.toString(val.size());
                }
            } else if (args.get(0).getClass() == Class.forName("ast.ListTree")) {
                ArrayList val = (ArrayList) ((ListTree) args.get(0)).accept(new InterpreterVisitor());
                return Integer.toString(val.size());
            } else if (args.get(0).getClass() == Class.forName("ast.LiteralTree")) {
                String val = ((LiteralTree)args.get(0)).getSymbol().toString();
                return Integer.toString(val.length());
            }
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(LengthFunction.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
}
